import React, { useEffect, useRef, useState } from "react";
import { Table, Row, Col, Input, Form, Button, Switch, Space, Divider, Image, message, Modal, Select, Cascader } from 'antd'
import Prefix from '../../components/prefix'
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import * as apis from '../../lib/api'
import * as tool from '../../lib/tool'
import http from '../../lib/http'
import _ from 'lodash'



const Index = () => {
    const [search, setSearch] = useState({page: 1,page_size: 20})
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState()
    const [seleckeys, setSeleckeys] = useState([])
    const [orgCategory, setOrgCategory] = useState([])
    const [pubCategory, setPubCategory] = useState([])

    const loadData = async (s) => {
        try {
            let category_id = 0
            let second_category_id = 0
            let three_category_id = 0
            if(s.category_id && s.category_id[0]){
                category_id = s.category_id[0]
            }
            if(s.category_id && s.category_id[1]){
                second_category_id = s.category_id[1]
            }
            if(s.category_id && s.category_id[2]){
                three_category_id = s.category_id[2]
            }
            s.is_pub = 1
            setData(await http.post(apis.DESIGN_ADMIN_LIST,Object.assign(s,{category_id,second_category_id,three_category_id})))
            setSeleckeys([])
        } catch (error) {
            
        }
    }

    const onSearch = async (values) => {
        let cpSearch = {...search}
        cpSearch.name = values?.name
        cpSearch.category_id = values?.category_id
        cpSearch.page = 1
        cpSearch.status = values?.status
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const pageSearch = async (page,page_size) => {
        let cpSearch = {...search}
        cpSearch.page_size = page_size
        cpSearch.page = page
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const showChange = async (checked,v) => {
        const cpData = _.cloneDeep(data)     
        const index = cpData?.list?.findIndex(m => m.id === v.id)
        if(index !== -1){
            cpData.list[index].status = checked ? 1:2
            setLoading(true)
            try {
                await http.post(apis.DESIGN_ADMIN_SHOW_UPDATE,{id: v.id,status: cpData.list[index].status})
            } catch (error) {
                
            }
            setLoading(false)
            setData(cpData)
        }
    }

    const del = async (ids) => {
        setLoading(true)
        try {
            await http.post(apis.DESIGN_ADMIN_DELETE,{ids})
            message.success("操作成功")
            await loadData(search)
        } catch (error) {
            
        }
        setLoading(false)
    }

    useEffect(()=>{
        setLoading(true)
        loadData(search).then(r => {
            setLoading(false)
        })
        http.post(apis.DESIGN_ADMIN_CATEGORY_LIST,{is_pub: 1, status: 1}).then(r => {
            setPubCategory(tool.handleLevelData(r))
            setOrgCategory(r)
        })
        // eslint-disable-next-line
    },[])

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '名字',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags'
        },
        {
            title: '所属分类',
            dataIndex: 'category_id',
            key: 'category_id',
            render: (v,r) => {
                const cs = [r.pub_category_id,r.second_pub_category_id,r.three_pub_category_id]
                const txt = []
                for(let i=0;i<cs.length;i++){
                    let f = orgCategory.find(s => s.id === cs[i])
                    if(f){
                        txt.push(f.name)
                    }
                }
                return <span>{txt.join()}</span>
            }
        },
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            render: (v) => (
                <Image src={process.env.REACT_APP_OSS_URL+v+"?x-oss-process=image/resize,w_300"} width={60} height={60} fallback="" />
            )
        },
        {
            title: '是否显示',
            dataIndex: 'status',
            key: 'status',
            render: (v,r) => (
                <Switch checked={v === 1} onChange={(e) => showChange(e,r)} />
            )
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at'
        },
        {
            title: '操作',
            dataIndex: 'a',
            key: 'a',
            render: (v,r) => (
                <>
                    <Button loading={loading} type="link" onClick={async () => {
                        setLoading(true)
                        let token = await http.get(apis.PC_TOKEN)
                        setLoading(false)
                        let domA = document.createElement("a")
                        domA.href = `${process.env.REACT_APP_PC_URL}/login/auto?id=${r.id}&token=${token}`
                        domA.target = "_blank"
                        domA.click()
                    }} style={{padding: 0}}>设计</Button>
                    <Divider type="vertical" />
                    <Button loading={loading} style={{padding: 0}} type="link" danger onClick={()=> {
                         Modal.confirm({
                            title: "提示",
                            content: <p>确定删除吗?</p>,
                            onOk: async () => {
                                await del([r.id])
                            }
                        })
                    }}>删除</Button>
                </>
            )
        }
    ]

    return (
        <div>
            <Form onFinish={onSearch}>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item name="name">
                            <Prefix label="名称">
                                <Input allowClear placeholder="请输入名称" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="category_id">
                            <Prefix label="所属分类">
                                <Cascader allowClear options={pubCategory} placeholder="请选择" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="status">
                            <Prefix label="是否禁用">
                                <Select allowClear placeholder="请选择">
                                    <Select.Option value={1}>启用</Select.Option>
                                    <Select.Option value={2}>禁用</Select.Option>
                                </Select>
                            </Prefix>
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item>
                            <Space>
                                <Button loading={loading} type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Space>
                <span>已选 {seleckeys?.length} 条</span>
                <Button danger disabled={seleckeys?.length === 0} onClick={() => {
                    Modal.confirm({
                        title: "提示",
                        content: <p>确定删除 <span style={{color: 'red'}}>{seleckeys?.length}条</span> 数据吗?</p>,
                        onOk: async () => {
                            await del(seleckeys)
                        }
                    })
                }}>批量删除</Button>
            </Space>
            <div style={{height: 12}}></div>
            <Table 
                rowKey={'id'}
                dataSource={data?.list || []} 
                loading={loading} 
                columns={columns}
                pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    onChange: pageSearch,
                    total: data?.total,
                    current: data?.page,
                    pageSize: data?.page_size
                }}
                scroll={{
                    y: 'calc(100vh - 510px)'
                }}
                rowSelection={{
                    onChange: (keys) => {
                        setSeleckeys(keys)
                    },
                    selectedRowKeys: seleckeys
                }}
            />
        </div>
    )
}

export default Index